<template>
    <div class="flex_col m5 p10 card">
        <label class="flex_center_self">软件更新</label>
        <div class="flex_row_center mt5">
            <label>控制板:</label>
            <el-select style="width: 200px;" v-model="ctx.address">
                <el-option
                    v-for="(item, index) in devices"
                    :key="index"
                    :label="item.name"
                    :value="item.address"
                />
            </el-select>
        </div>
        <div class="flex_row_center mt5">
            <input accept=".bin" type="file" @change="inputChanged" ref="file_input" style="display: none;"/>
            <el-button @click="onClickOpen">打开文件</el-button>
        </div>
    </div>
</template>

<script lang="ts" setup>

import { devices, deviceWithAddress, weight } from '@/service/address';
import { setOtaCb } from '@/service/info';
import { otaWithData } from '@/service/ota';
import { runAction } from '@/utils/ui';
import { reactive, ref } from 'vue';

interface Ctx {
    address: number,
}
const ctx = reactive<Ctx>({
    address: weight.address,
});
const file_input = ref<HTMLInputElement | null>(null);

async function inputChanged(event: Event) {
    const input = event.target as HTMLInputElement;
    const files = input.files;
    if (files == null) {
        return;
    }
    if (files.length == 0) {
        return;
    }
    const file = files.item(0);
    if (file == null) {
        return;
    }
    input.value = '';
    const data = new Uint8Array(await file.arrayBuffer());
    const address = ctx.address;
    let device = deviceWithAddress(address);
    await runAction(`${device.name} OTA升级`, ``, async (dialog) => {
        setOtaCb((msg) => {
            dialog.setMsg(msg);
        });
        await otaWithData(address, data);
    });
}

function onClickOpen() {
    file_input.value?.click();
}

</script>
